package top.lyjwn.todo.weinxin.bjnews;

import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import top.lyjwn.todo.weinxin.api.bjnews.GetBaseAccessToken;
import top.lyjwn.todo.weinxin.bjnews.service.WXBUserService;

import java.util.concurrent.*;

/**
 * 微信公众号
 *
 * @author luoyujie
 */
public class WXBjnews {

    private final static Logger logger = LoggerFactory.getLogger(WXBjnews.class);

    /**
     * 定时获取公众号的token
     */
    private final static ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

    /**
     * 用户token刷新
     */
    private final static ExecutorService executor = new ThreadPoolExecutor(1, 4, 5, TimeUnit.SECONDS, new LinkedTransferQueue<Runnable>());

    @Autowired
    private GetBaseAccessToken getBaseAccessToken;

    /**
     * 微信公众号令牌
     */
    private BjnewsAccessToken accessToken;

    public final void work() {
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                getBaseAccessToken();
            }
        }, 0, accessToken.getExpires_in() - (10 * 1000), TimeUnit.MILLISECONDS);
        logger.info("微信公众号对接程序启动..");
        // 用户 AccessToken刷新线程
        executor.execute(new WXBUserService());
//		Thread thread2 = new Thread(new WXBUserService());
        logger.info("微信公众号用户access_token自动刷新程序启动..");
    }

    private void getBaseAccessToken() {
        JSONObject responseToJSON = getBaseAccessToken.getResultJSONObject();
        if (responseToJSON.getString("errmsg") != null) {
            logger.error(responseToJSON.getString("errmsg"));
        } else {
            logger.info("access_token" + responseToJSON.toJSONString());
        }
        accessToken = BjnewsAccessToken.builder(responseToJSON);
    }


    public BjnewsAccessToken getAccessToken() {
        return accessToken;
    }
}
